const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🧪 测试施工队伍数据插入')
  
  try {
    // 测试数据库连接
    console.log('🔗 测试数据库连接...')
    const collections = await db.collection('construction_teams').limit(1).get()
    console.log('✅ 数据库连接成功')
    
    // 插入一条测试数据
    const testTeam = {
      id: 'test_team_001',
      name: '测试施工队伍',
      type: 'individual',
      typeName: '个人师傅',
      category: 'electrical',
      categoryName: '电气工程',
      avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200',
      experience: '10年',
      rating: 4.5,
      completedProjects: 50,
      location: '贵州省贵阳市',
      phone: '138****0000',
      specialties: ['测试专业'],
      certifications: ['测试证书'],
      description: '这是一条测试数据',
      priceRange: '100-200元/天',
      status: 'available',
      joinDate: '2024-01-01',
      tags: ['测试标签'],
      createTime: new Date(),
      updateTime: new Date()
    }
    
    console.log('📦 开始插入测试数据...')
    const result = await db.collection('construction_teams').add({
      data: testTeam
    })
    
    console.log('✅ 测试数据插入成功:', result)
    
    // 查询验证
    const queryResult = await db.collection('construction_teams')
      .where({ id: 'test_team_001' })
      .get()
    
    console.log('🔍 查询验证结果:', queryResult.data.length, '条数据')
    
    return {
      success: true,
      message: '测试数据插入成功',
      data: {
        insertResult: result,
        queryResult: queryResult.data
      }
    }
    
  } catch (error) {
    console.error('❌ 测试失败:', error)
    return {
      success: false,
      error: error.message,
      stack: error.stack
    }
  }
}
